package com.imooc.alllearning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imooc.alllearning.common.PageQuery;
import com.imooc.alllearning.common.PageResult;
import com.imooc.alllearning.domain.dto.UserDTO;
import com.imooc.alllearning.domain.dto.UserQueryDTO;
import com.imooc.alllearning.domain.entity.UserDO;
import com.imooc.alllearning.mapper.UserMapper;
import com.imooc.alllearning.service.UserService;
import com.imooc.alllearning.util.ValidatorUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import javax.swing.text.html.Option;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by lijian on 2020/3/27 16:18
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public int save(UserDTO userDTO) {
        UserDO userDO = new UserDO();
        // TODO 浅拷贝 属性名相同才能拷贝
        BeanUtils.copyProperties(userDTO, userDO);
        return userMapper.insert(userDO);
    }

    @Override
    public int update(Long id, UserDTO userDTO) {
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(userDTO, userDO);
        userDO.setId(id);
        return userMapper.updateById(userDO);
    }

    @Override
    public int delete(Long id) {
        return userMapper.deleteById(id);
    }

    @Override
    public PageResult<List<UserDTO>> query(PageQuery<UserQueryDTO> pageQuery) {
        // 手动校验功能
        ValidatorUtils.validate(pageQuery);
        Page page = new Page(pageQuery.getPageNo(),pageQuery.getPageSize());
        UserDO query = new UserDO();
        BeanUtils.copyProperties(pageQuery.getQuery(), query);
        //TODO 如果属性不一致 需要做特殊处理
        QueryWrapper queryWrapper = new QueryWrapper(query);
        //查询
        IPage<UserDO> iPage = userMapper.selectPage(page, queryWrapper);
        //结果解析
        PageResult result = new PageResult();
        result.setPageNo((int)iPage.getCurrent());
        result.setPageSize((int)iPage.getSize());
        result.setTotal(iPage.getTotal());
        result.setPageNum(iPage.getPages());
        //对数据进行转换
        List<UserDTO> userDTOList = Optional.ofNullable(iPage.getRecords())
                .map(List::stream)
                .orElseGet(Stream::empty)
                .map(userDO -> {
                    UserDTO userDTO = new UserDTO();
                    BeanUtils.copyProperties(userDO, userDTO);
                    return userDTO;
                }).collect(Collectors.toList());
        result.setData(userDTOList);
        return result;
    }
}
